package com.getword.web.controller;


import com.getword.domain.User;
import com.getword.domain.Video;
import com.getword.service.VideoService;
import com.getword.utils.DataUtil;
import com.getword.utils.PathUtil;
import com.getword.utils.SpringContextUtil;
import com.getword.web.model.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/video")
public class ApiVideoController {
    @Autowired
    private VideoService service;
    @Autowired
    private MongoTemplate mongo;

    public static String VIDEO_FILENAME = "videoFileName";
    public static String CAPTION_FILENAME = "captionFileName";
    public static String VIDEO = "video";

    // 上传字幕文件
    @PostMapping("/captionFile")
    public Result uploadCaption(MultipartFile file, HttpServletRequest request) {
        // 如果session中存在字幕文件，则将session中的字幕文件删除
        // 如果session中已经保存了字幕文件，即当前用户已经上传了字幕文件,需要删除
//        if (video.getCaptionOriginalName() != null) {
//            File captionFile = new File(PathUtil.basePath + "static/upload/video/" + video.getCaptionOriginalName());
//            if (captionFile.exists()) {
//                captionFile.delete();
//            }
//        }
        // 重新保存字幕文件
        return service.uploadCaption(file, request);
    }

    // 清除session中的文件
    @PostMapping("/clearFile")
    public void clearFile(HttpServletRequest request) {
        // 如果session中存在未保存的视频、字幕文件，需要删除
        String videoFilename = (String) request.getSession().getAttribute(VIDEO_FILENAME);
        if (videoFilename != null) {
            String filePath = PathUtil.basePath + "static/upload/video/" + videoFilename;
            File videoFile = new File(filePath);
            System.out.println(DataUtil.sizeOf(FileUtils.sizeOf(videoFile)));
            if (videoFile.exists()) {
                videoFile.delete();
            }
        }

    }

    // 上传封面
    @PostMapping("/cover")
    public Result uploadCover(MultipartFile file, HttpServletRequest request){
        return service.uploadCover(file, request);
    }

    @GetMapping("/preview")
    public Result preview(HttpServletRequest request) {
        Video video = (Video) request.getSession().getAttribute(VIDEO);
        if (video == null || video.getVideoFilename() == null) {
            return Result.fail("请长传视频");
        }
        if (video == null || video.getCaptionFilename() == null) {
            return Result.fail("请长传字幕");
        }
        String videoFilename = video.getVideoFilename();
        String captionFilename = video.getCaptionFilename();
        return Result.success(new HashMap<String, String>() {{
            put("videoPath", "/upload/video/" + videoFilename);
            put("captionPath", "/upload/video/" + captionFilename);
        }});
    }

    @GetMapping("/init")
    public Result initVideo(HttpServletRequest request) {
        Video video = (Video) request.getSession().getAttribute(VIDEO);
        return Result.success(video);
    }

    // 上传视频，包括标题、大纲归属等信息
    @PostMapping
    public Result create(String title, Long outlineId, String detailNum, HttpServletRequest request) {
        Video video = (Video) request.getSession().getAttribute(VIDEO);
        if(video == null||video.getVideoFilename() == null){
            return Result.fail("请上传视频");
        }
        if(video.getCaptionFilename() == null){
            return Result.fail("请上传字幕");
        }
        video.setTitle(title);
        video.setUploadTime(new Date());
        Result result = service.saveVideo(video, outlineId, detailNum);
        request.getSession().setAttribute(VIDEO, null);
        return result;
    }


    // 视频展示, 根据grade,course查询
    @GetMapping
    public Result query(int page, int size, Long gradeId, Long courseId){
        Pageable pageable = PageRequest.of(page-1, size);
        return service.getVideos(pageable, gradeId, courseId);
    }
    // 视频管理, 根据grade,course，title查询
    @GetMapping("/query")
    public Object queryManage(int page, int size, Long gradeId, Long courseId, String title){
        User user = new User(SpringContextUtil.getLoginUser().getId());

        Pageable pageable= PageRequest.of(page-1, size);
        Page<Video> videos = service.getVideoPage(pageable, gradeId, courseId, title, user);
        Map<String, Object> result = new HashMap<>();
        if(videos!=null){
            result.put("code", 0);
            result.put("msg", "");
            result.put("count", videos.getTotalElements());
            result.put("data", videos.getContent());
        }else{
            result.put("code", 1);
            result.put("msg", "服务器错误");
            result.put("count", 0);
        }
        return result;
    }

    // 根据视频ID查询
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable String id){
        return service.getVideoById(id);
    }


    // 修改视频信息，标题、封面
    public Result update(){
        return null;
    }

    @PutMapping("/updateUser")
    public Result updateUser(String id){
        Update update = Update.update("user", new User(SpringContextUtil.getLoginUser().getId()));
        mongo.updateMulti(Query.query(Criteria.where("videoExt").is("mp4")), update, Video.class);
        return null;
    }

    // 添加情感分析内容
//    @PutMapping("/sentiment")
//    public Result sentiment(Video video){
//        return service.addSentiment(video);
//    }

    // 点赞
    @PostMapping("/zan")
    public Result zan(String videoId){
        return service.zan(videoId);
    }

    @GetMapping("/zanState")
    public Result zanState(String videoId){
        return service.getZanState(videoId);
    }

    @GetMapping("/zanCount")
    public Result zanCount(String videoId){
        return service.getZanCount(videoId);
    }

}
